// pages/admin/login/index.js
const api = require('../../../../utils/api.js');

Page({
  data: {
    username: '',
    password: '',
    showPassword: false,
    loginDisabled: false
  },

  onLoad() {
    // 检查是否已经登录
    const adminToken = wx.getStorageSync('adminToken');
    if (adminToken) {
      this.checkAdminStatus();
    }
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  async handleLogin() {
    const { username, password } = this.data;

    if (!username.trim()) {
      wx.showToast({
        title: '请输入管理员账号',
        icon: 'none'
      });
      return;
    }

    if (!password.trim()) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }

    this.setData({ loginDisabled: true });

    try {
      const result = await api.request({
        url: 'admin/login',
        method: 'POST',
        data: {
          username: username.trim(),
          password: password.trim()
        }
      });

      if (result.code === 0) {
        // 保存管理员信息
        wx.setStorageSync('adminToken', result.data.token);
        wx.setStorageSync('adminInfo', result.data.adminInfo);

        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 跳转到管理后台首页
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/admin/dashboard/index'
          });
        }, 1500);
      } else {
        wx.showToast({
          title: result.msg || '登录失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loginDisabled: false });
    }
  },

  async checkAdminStatus() {
    try {
      const result = await api.request({
        url: 'admin/home',
        method: 'GET'
      });

      if (result.code === 0) {
        // 已登录，直接跳转
        wx.navigateTo({
          url: '/pages/admin/dashboard/index'
        });
      } else {
        // 登录已过期，清除本地存储
        wx.removeStorageSync('adminToken');
        wx.removeStorageSync('adminInfo');
      }
    } catch (error) {
      console.error('检查管理员状态失败:', error);
      wx.removeStorageSync('adminToken');
      wx.removeStorageSync('adminInfo');
    }
  }
});